package com.cyj.controller;
import com.cyj.entity.Admin;
import com.cyj.entity.FileEntity;
import com.cyj.entity.User;
import com.cyj.service.UserService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/registerView")
    public String registerUser(Model model){
        User user = new User();
        model.addAttribute(user);
        return "register";
    }

    @RequestMapping("/userDetails")
    public String userDetails(){
        return "userDetails";
    }

    @RequestMapping("/userMain")
    public String userMain(){
        return "userMain";
    }

    @RequestMapping(value="/userLogin",produces = "text/html;charset=utf-8")
    public String userLogin(User user, Model model, HttpSession session){
        Map<String,Object> map =  new HashMap<String,Object>();
        map.put("userName",user.getUserName());
        map.put("userPassword",user.getUserPassword());
        User loginUser = userService.selectUser(map);

        if (loginUser!=null){
            user.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            userService.updateUser(user);
            session.setAttribute("user",userService.selectUser(map));
            System.out.println(userService.selectUser(map));

            return "redirect:/user/userMain";
        }else {

            model.addAttribute("error","账号或密码错误");
            return "forward:../userLogin.jsp";
        }
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(User user, Model model, BindingResult result){
        System.out.println(user);

        user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        int num = userService.addUser(user);

        if(num>0){
            model.addAttribute("error","二次元用户注册成功");
            return "forward:../userLogin.jsp";
        }else {
            model.addAttribute("error","二次元用户注册失败了(已存在该用户)");
            return "register";
        }
    }

    @RequestMapping(value = "users")
    public String users(Locale locale){
        return "userList";
    }

    @ResponseBody
    @RequestMapping(value = "/userList",produces = "application/json;charset=utf-8")
    public Map userList(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model) throws IOException {
        Map map = new HashMap<>();

        PageInfo page  = userService.selectUserList(map,pn,5);

        map.put("pageInfo",page);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/allUserList",produces = "application/json;charset=utf-8")
    public Map allUserList(Model model) throws IOException {
        Map<String,Object> map = new HashMap<String,Object>();

        List<User> list = userService.selectAllUserList(map);
        if(list.size()>0){
            map.put("code", 200);
            map.put("msg", "用户查找成功");
            map.put("data",list);
        }else {
            map.put("code", 100);
            map.put("msg", "用户查找失败");
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/userBy",produces = "application/json;charset=utf-8")
    public Map userBy(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        Integer userId = Integer.parseInt(request.getParameter("userId"));

        map.put("userId",userId);

        User user = userService.selectUser(map);

        if(user!=null){
            map.put("code", 200);
            map.put("msg", "用户查找成功");
            map.put("data",user);
        }else {
            map.put("code", 100);
            map.put("msg", "用户查找失败");
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/updateUser",produces = "application/json;charset=utf-8")
    public Map updateUser(HttpServletRequest request,HttpSession session){

        Map<String, String[]> map = request.getParameterMap();
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        User user = new User();

        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        int num = userService.updateUser(user);

        Map<String,Object> map2 = new HashMap<String,Object>();

        if (num>0){
            if(session.getAttribute("user")!=null){
                session.removeAttribute("user");
                map2.put("userId",userId);
                session.setAttribute("user",userService.selectUser(map2));
            }


            map2.put("code", 200);
            map2.put("msg", "用户修改成功");
        }else {
            map2.put("code", 100);
            map2.put("msg", "用户修改失败");
        }

        return map2;
    }

    @ResponseBody
    @RequestMapping(value = "/delUser",produces = "application/json;charset=utf-8")
    public Map delUser(@RequestBody User user){

        Map<String,Object> map = new HashMap<String,Object>();

        user.setIsDelete(1);

        int num = userService.updateUser(user);

        if(num>0){
            map.put("code",200);
            map.put("msg","账号注销成功！");
        }else{
            map.put("code",100);
            map.put("msg","账号注销失败！");
        }


        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/addUser",produces = "application/json;charset=utf-8")
    public Map addUser(@RequestBody User user){

        Map<String,Object> map02 = new HashMap<String,Object>();

        System.out.println(user);

        user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        int num = userService.addUser(user);


        if(num>0){
            map02.put("code",200);
            map02.put("msg","添加用户成功！");
        }else{
            map02.put("code",100);
            map02.put("msg","添加用户失败！");
        }

        return map02;
    }

    @ResponseBody
    @RequestMapping(value = "/uploadPicture",produces = "application/json;charset=utf-8")
    public Map uploadPicture(HttpServletRequest request, FileEntity entity, HttpSession session){

        //设置要存放图片的目录 (例如：c:/tomcat/webapp/upload)
        String realpath = request.getServletContext().getRealPath("/")+"upload/";

        String fileName = entity.getUploadFile().getOriginalFilename();
        System.out.println(fileName);

        //把路径封装为file对象（因为file可以判断文件或者目录是否存在，如果不存在就可以创建）
        File targetPath = new File(realpath+fileName);

        //判断文件或者路径是否存在
        if (!targetPath.exists()){
            targetPath.mkdirs();
        }
        try {
            //使用MultipartFile的transferTo方法保存从前端传过来MultipartFile对象
            entity.getUploadFile().transferTo(targetPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取要存到数据库里面的路径
        String picture = "http://192.168.44.48:8080"+request.getContextPath()+"/upload/"+fileName;
        System.out.println(picture);

        Integer userId = Integer.parseInt(request.getParameter("userId"));

        User user = new User();
        user.setUserId(userId);
        user.setPicture(picture);

        System.out.println(user);

        int num = userService.updateUser(user);

        Map<String,Object> map = new HashMap<String,Object>();

        if (num>0){
            session.removeAttribute("user");
            map.put("userId",userId);
            session.setAttribute("user",userService.selectUser(map));

            map.put("code", 200);
            map.put("msg", "用户头像上传成功");
        }else {
            map.put("code", 100);
            map.put("msg", "用户头像上传失败");
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/logout",produces = "application/json;charset=utf-8")
    public Map logout(HttpSession session){
        session.removeAttribute("user");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code", 200);
        map.put("msg", "退出登录成功");

        return map;
    }

}
